// 运行时配置

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
// import { ProLayoutProps } from '@ant-design/pro-layout';

import {
  ApartmentOutlined,
  AppstoreAddOutlined,
  AppstoreOutlined,
  BlockOutlined,
  BugOutlined,
  CodepenOutlined,
  DatabaseOutlined,
  ExperimentOutlined,
  FieldStringOutlined,
  GoldOutlined,
  MenuOutlined,
  SolutionOutlined,
  TableOutlined,
  TeamOutlined,
  UserOutlined,
  UserSwitchOutlined,
  VerifiedOutlined,
} from '@ant-design/icons';

import { history, RequestConfig, RunTimeLayoutConfig } from 'umi';
import { AccessTokenConstant, CurrentUser, isLogin, loginStorage, logout } from '@/pages/user/login/service';
import { notification } from 'antd';
import { ProLayoutProps } from '@ant-design/pro-layout';
import { isDevelopmentEnvironment } from '@/utils/util';

/**
 * <a href='https://umijs.org/docs/max/request#request'>request</a>
 */
export const request: RequestConfig = {
  requestInterceptors: [
    (url, options) => {
      const key = loginStorage.get(AccessTokenConstant.access) || 'token';
      const tokenValue = loginStorage.get(AccessTokenConstant.name);
      const requestHeaders = { ... options?.headers };
      if (key && tokenValue) {
        requestHeaders[key] = tokenValue;
      }
      return {
        url,
        options: {
          ... options,
          headers: requestHeaders,
        },
      };
    },
    // (error) => {
    //     return Promise.reject(error);
    // }
  ],
  responseInterceptors: [
    (response) => {
      if (isDevelopmentEnvironment()) {
        notification.open({
          placement: 'bottomLeft',
          message: '响应拦截器',
          icon: <BugOutlined style={ { color: 'red' } } />,
          description: response?.statusText,
          style: { width: '50vw' },
        });
      }
      if (response?.status === 401) {
        notification.error({
          placement: 'topLeft',
          type: 'error',
          message: '无权访问',
          description: response?.statusText,
        });
        loginStorage.clear();
        history.push({ pathname: '/user/login' });
      } else {
        // 可以根据 response?.data?.code (AppResult<any>) 来做逻辑处理
      }

      return response;
    },
  ],
};

declare type InitialStateType = CurrentUser & ProLayoutProps;

/**
 * <a href='https://umijs.org/docs/max/data-flow#%E5%85%A8%E5%B1%80%E5%88%9D%E5%A7%8B%E7%8A%B6%E6%80%81'>getInitialState</a>
 */
export async function getInitialState(): Promise<InitialStateType> {
  // 初始化设置
  return {};
}

/**
 * <a href='https://umijs.org/docs/api/runtime-config#layout'>layout</a>
 * @param props
 */
export const layout: RunTimeLayoutConfig = (props: any) => {
  // const { REACT_APP_ENV, UMI_ENV } = process.env;
  console.log(props);
  const {} = props;
  // console.log(process.env, active);

  return {
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    menu: {
      locale: false,
      type: 'sub',
      // loading: true,
    },
    // loading: props?.initialState?.loading,
    // 导航布局
    layout: 'mix',
    splitMenus: true,
    // 登录页面不显示布局
    pure: !isLogin(),
    // colorPrimary: '#ccffdd',
    childrenRender: (dom, p) => {
      console.log(dom, p);
      return dom;
    },
    logout: async (init) => {
      const response = await logout();
      console.log(init, response);
      history.push('/');

      return Promise.resolve();
    },
    onPageChange: (location) => {
      console.log(location);
      if (location?.pathname === '/dev') {
        history.push({
            pathname: '/dev/table', search: '?a=b&c=d',
            hash: 'anchor',
          },
          {
            some: 'state-data',
          });
      }
    },
    // loading: true,
    // rightContentRender: () => {
    //   return <a>xwwwwwwwwwwv</a>
    // },
    // rightRender: () => {
    //   return <a>和 rightContentRender 一样的效果</a>;
    // },
    colorWeak: true,
    // navTheme: 'realDark',
    theme: 'dark',
    waterMarkProps: {
      content: [ 'WaterMark', '水印' ],
    },
    menuDataRender: menuData => {
      return [
        { path: '/', name: '主页' },
        {
          path: '/sys',
          name: '系统管理',
          icon: <GoldOutlined />,
          children: [
            { path: '/sys/user', name: '用户管理', icon: <UserOutlined /> },
            { path: '/sys/tenant', name: '租户管理', icon: <ApartmentOutlined /> },
            { path: '/sys/dept', name: '部门管理', icon: <TeamOutlined /> },
            { path: '/sys/role', name: '角色管理', icon: <UserSwitchOutlined /> },
            { path: '/sys/menu', name: '菜单管理', icon: <MenuOutlined /> },
            { path: '/sys/permission', name: '权限管理', icon: <MenuOutlined /> },
            { path: '/sys/token', name: '在线用户', icon: <VerifiedOutlined /> },
            { path: '/sys/log', name: '日志管理', icon: <SolutionOutlined /> },
          ],
        },
        {
          path: '/dev',
          name: '开发平台',
          icon: <ExperimentOutlined />,
          children: [
            { path: '/dev/database', name: '数据源管理', icon: <DatabaseOutlined /> },
            { path: '/dev/table', key: 'abc', name: '数据表管理', icon: <TableOutlined /> },
            { path: '/dev/generator', name: '代码生成', icon: <CodepenOutlined /> },
            {
              path: '/dev/meta',
              name: '元数据管理',
              icon: <BlockOutlined />,
              children: [
                { path: '/dev/meta/field', name: '字段管理', icon: <FieldStringOutlined /> },
                { path: '/dev/meta/template', name: '模板管理', icon: <AppstoreOutlined /> },
                { path: '/dev/meta/templateGroup', name: '模板分组', icon: <AppstoreAddOutlined /> },
              ],
            },
          ],
        },
      ];
    },
  };
};
